package com.dlc.beijingrfid.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import butterknife.BindView;
import com.dlc.commonlibrary.adapter.BaseRecyclerAdapter;
import com.dlc.commonlibrary.ble.BleConstant;
import com.dlc.commonlibrary.ble.BleHelper;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.HandheldDeviceAdapter;
import com.dlc.beijingrfid.base.BaseFragment;
import com.dlc.beijingrfid.helper.PreHelper;
import com.dlc.beijingrfid.model.HandheldDevice;
import java.util.ArrayList;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.dlc.commonlibrary.ble.BleHelper.REQUEST_ENABLE_BT;
import static com.dlc.commonlibrary.ble.BleHelper.bTAdapter;


/**
 * Created by John on 2017/7/18.
 */

public class BluetoothFragment extends BaseFragment {

    @BindView(R.id.btn_refresh) Button mBtnRefresh;
    @BindView(R.id.recycler_view) RecyclerView mRecyclerView;
    ArrayList<HandheldDevice> devices = new ArrayList<>();

    HandheldDeviceAdapter adapter;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_bluetooth;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // TODO: 2017/7/18 假数据 

//        for (int i = 0; i < 1000; i++) {
//            devices.add(new HandheldDevice("手持设备" + i, i % 2 == 0));
//        }

        registerBleRv();

        adapter = new HandheldDeviceAdapter();
        adapter.setNewData(devices);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, BaseRecyclerAdapter.CommonHolder holder, final int position) {
                 final BluetoothDevice device = adapter.getItem(position).getDevice();
                showWaitingDialog(getResources().getString(R.string.ble_connect_ing),true);
                Observable.create(new Observable.OnSubscribe<Boolean>() {
                    @Override
                    public void call(final Subscriber<? super Boolean> subscriber) {
                        //已经连接不处理
                        if(adapter.getItem(position).isConnected()){
                            adapter.getItem(position).setConnected(false);
                            BleHelper.getInstance().stopDevice();
                        }

                        BleHelper.getInstance().connectBle(device.getAddress(), new BleHelper.BleConnectCall() {
                            @Override
                            public void connectCall(boolean isSuccess) {
                                subscriber.onNext(isSuccess);
                                subscriber.onCompleted();
                            }
                        });
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                dismissWaitingDialog();
                            }

                            @Override
                            public void onNext(Boolean isSuccess) {
                                dismissWaitingDialog();

                                if(isSuccess.booleanValue()) {
                                    //设置连接状态
                                    adapter.getItem(position).setConnected(true);
                                    //保存连接过的设备地址
                                    PreHelper.saveBleDevice(adapter.getItem(position).getDevice().getAddress());
                                    adapter.notifyDataSetChanged();

                                } else {
                                    Toast.makeText(getActivity(),getString(R.string.connnect_default),Toast.LENGTH_SHORT).show();
                                }
                            }
                        });



            }
        });
        connectBle();
        initBus();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiver);
    }

    /**
     * 注册register
     */
    private void registerBleRv(){

        // 注册一个广播接收器来接受系统的广播
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(BluetoothDevice.ACTION_FOUND); // 发现设备的广播
        getActivity().registerReceiver(mReceiver, intentfilter); // Don't forget to unregister during onDestroy
    }

    /**
     * 监听事件
     */
    private void initBus(){

        mBtnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                connectBle();
            }
        });
    }

    private void connectBle(){
        showWaitingDialog("正在搜索...",true);
        new Handler(getActivity().getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
               dismissWaitingDialog();
            }
        },3000);

        adapter.cleanNoConnectDev();
        BleHelper.getInstance().checkBT(getContext());

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_ENABLE_BT){
            if(bTAdapter.isDiscovering()){
                bTAdapter.cancelDiscovery();
            }
            bTAdapter.startDiscovery();
        }

    }

    /**
     * 广播接收器 创建一个接收ACTION_FOUND广播的BroadcastReceiver
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("action",action);
            BluetoothDevice device = null;

            // 发现设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 从Intent中获取设备对象
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 如果它已经配对，跳过它，因为它已经被列入

                    if(!TextUtils.isEmpty(device.getName()))
                        if(device.getName().contains(BleConstant.RFID_DEVICE_NAME)){
                            LogPlus.e("ble","device:"+device.getName());
                            adapter.addData(new HandheldDevice("手持设备_"+device.getAddress(),checkDeviceConnect(device),device));
                        }
                }
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
                    == BluetoothAdapter.STATE_OFF){
                    if (adapter != null){
                        adapter.setNoConnectDev();
                    }
                    BleHelper.getInstance().stopReadValue();
                    BleHelper.getInstance().stopBle();
                }

            }

        }
    };

    /**
     * 检查设备是否已经连接
     * @param device
     * @return
     */
    private boolean checkDeviceConnect(BluetoothDevice device){
        BluetoothDevice connectDevice = BleHelper.getInstance().getConnectDevice();
        if(connectDevice != null) {
            if (device.getAddress().equals(connectDevice.getAddress())){
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

}
//xianggangshangmi
//http://www.rfidxidi.com/user_api/
